<template>
  <!-- 模拟面试 -->
  <Interview
    v-if="chatStore.menuId == 2 && interviewShow && loadingStatus"
    :chatId="chatId"
    @update="handleUpdate"
  />
  <div class="chat-box" v-if="!interviewShow">
    <!-- 模拟面试:身份确认 -->
    <div class="identityInformation" v-show="chatStore.menuId == 2">
      <div class="information">
        <div class="identity">
          <p>你选择的身份是：{{ identity }}</p>
          <p>面试岗位为：{{ occupation }}</p>
        </div>
        <div class="identity-btn">
          <button @click="restartInterview">重新模拟面试</button>
        </div>
      </div>
    </div>
    <!-- 聊天 -->
    <div class="chat-main">
      <div class="chat-content" ref="chatContent" @scroll="handleScroll">
        <!-- 历史聊天记录 -->
        <div
          class="content-box"
          v-for="(item, index) in historyChatList"
          :key="index"
          :class="item.role == 'user' ? 'user-content' : ''"
        >
          <div class="user-box" v-if="item.role == 'user'">
            <div class="chat-message">
              <div class="message-item">{{ item.content }}</div>
            </div>
            <div class="chat-head">
              <img :src="userStore.userInfo.logo" />
            </div>
          </div>
          <div class="system-box" v-else>
            <div class="chat-head">
              <img :src="aiLogo" />
            </div>
            <div class="chat-message">
              <div
                class="message-markdown"
                v-html="markdown(item.content)"
              ></div>
            </div>
          </div>
        </div>
        <!-- 实时对话 -->
        <div
          class="content-box"
          v-for="(item, index) in messageList"
          :key="index"
          :class="item.role == 'user' ? 'user-content' : ''"
        >
          <div class="user-box" v-if="item.role == 'user'">
            <div class="chat-message">
              <div class="message-item">{{ item.content }}</div>
            </div>
            <div class="chat-head">
              <img :src="userStore.userInfo.logo" />
            </div>
          </div>
          <div class="system-box" v-else>
            <div class="chat-head">
              <img :src="aiLogo" />
            </div>
            <div class="chat-message">
              <div
                class="message-markdown"
                v-html="markdown(item.content)"
              ></div>
            </div>
          </div>
        </div>
      </div>
      <div class="chat-footer">
        <div class="chat-input">
          <el-input
            v-model="messages"
            maxlength="3000"
            style="flex: 1"
            type="textarea"
            placeholder="请输入内容"
            resize="none"
            class="message-input"
            @keydown.enter.prevent="handleEnter"
            @compositionstart="handleStart"
            @compositionend="handleEnd"
          />
          <div class="dialogInput-right">
            <button class="dialog-btn" @click="sendMessage">
              <img src="@img/dialog/sending.png" alt="发送" />
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onBeforeMount, ref, nextTick, watch } from "vue";
import md from "@utils/markdown";
// 头像
import aiLogo from "@img/menu/logo.png";
// api
import { chatMessageList, chatGet } from "@api/chat";
// stores
import { useGlobalStore } from "@stores";
// 模拟面试组件
import Interview from "@views/interview/index.vue";
// 控制模拟面试显示
let interviewShow = ref(false);
// 更新模拟面试状态
const handleUpdate = () => {
  interviewShow.value = false;
  historyChatList.value = [];
  page.value = 0;
  loadingStatus.value = false;
  getChatMessageList();
  getChatInfo();
};
// 重新模拟面试
const restartInterview = () => {
  interviewShow.value = true;
};
// 获取身份
let identity = ref("");
let occupation = ref("");
const getChatInfo = async () => {
  const res = await chatGet(chatId.value);
  if (res.code != 0) return;
  identity.value = res.data.identity + res.data.workTime;
  occupation.value = res.data.occupation;
};
const userStore = useGlobalStore().userStore;
const chatStore = useGlobalStore().chatStore;
// 会话id
let chatId = ref();
// 输入框内容
const messages = ref("");
// 控制中文时enter发送
const composing = ref(false);
const handleEnter = () => {
  if (!composing.value) {
    sendMessage();
  }
};
// 监听中文开始事件
const handleStart = () => {
  composing.value = true;
};
// 监听中文结束事件
const handleEnd = () => {
  composing.value = false;
};
// 控制是否在发送消息状态
let isAnswering = ref(false);
// 消息列表
const messageList = ref([]);
// 发送消息
const sendMessage = async () => {
  if (!isAnswering.value) {
    const len = messageList.value.length;
    messageList.value[len] = {
      role: "user",
      content: messages.value,
      userId: userStore.userInfo.userId,
    };
    // 清空输入框内容
    messages.value = "";
    isAnswering.value = true;
    // 请求接口
    await initEventData();
    isAnswering.value=false
  } else {
    ElNotification.warning("AI正在回答中，请稍后......");
  }
};
// 处理数据流
const initEventData = async () => {
  // 定义header、添加token
  const headers = {
    "Content-Type": "application/json",
    Authorization: userStore.token ? userStore.token : "",
  };
  // 发送请求
  const res = await fetch("/api/xlx-chat//chatMessage/sendMessage", {
    headers,
    method: "POST",
    body: JSON.stringify({
      id: chatId.value,
      userId: userStore.userInfo.userId,
      question: messageList.value[messageList.value.length - 1].content,
    }),
  });
  if (res.status == 200) {
    const reader = res.body?.getReader();
    console.log(reader);
    const decoder = new TextDecoder("utf-8");
    const len = messageList.value.length;
    messageList.value[len] = {
      role: "system",
      content: "",
    };
    while (true) {
      // 原始数据、状态
      const { done, value } = await reader.read();
      if (done) break;
      const chunk = decoder.decode(value, { stream: true });
      try {
        const parseData = JSON.parse(chunk);
        const content = parseData.content;
        messageList.value[len].content += content.replace(
          messageList.value[len].content,
          ""
        );
        scrollToBottom();
      } catch (error) {
        console.log(error);
      }
    }
  }
};
const chatContent = ref(null);
// 滚动到底
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value?.scrollHeight;
    }
  });
};
// markdown格式化
const markdown = (text: string) => {
  return md.render(text);
};
import { useRoute } from "vue-router";
let route = useRoute();
// 历史聊天记录列表
const historyChatList = ref([]);
let page = ref<number>(0);
let pageSize = ref<number>(10);
let loadingStatus = ref<boolean>(false);
// 获取历史聊天记录
const getChatMessageList = async () => {
  if (loadingStatus.value) return;
  await nextTick();

  let oldHeight = chatContent.value?.scrollHeight;
  page.value++;
  const res = await chatMessageList({
    chatId: chatId.value,
    page: page.value,
    pageSize: pageSize.value,
  });
  historyChatList.value = res.data.concat(historyChatList.value);

  if (
    chatStore.menuId == 2 &&
    historyChatList.value.length &&
    page.value == 1
  ) {
    interviewShow.value = false;
    getChatInfo();
  } else if (chatStore.menuId == 2 && !historyChatList.value.length) {
    interviewShow.value = true;
  }
  if (chatStore.menuId != 2) {
    interviewShow.value = false;
  }
  await nextTick();

  let newHeight = chatContent.value?.scrollHeight;
  if (chatContent.value) {
    chatContent.value.scrollTop = newHeight - oldHeight;
  }

  if (res.data.length < pageSize.value) {
    loadingStatus.value = true;
  }
};
// 滚动监听
const handleScroll = () => {
  const { scrollTop } = chatContent.value;
  if (scrollTop <= 0 && historyChatList.value.length >= pageSize.value) {
    getChatMessageList();
  }
};
watch(
  route,
  async (newVal) => {
    chatId.value = route.query.id;
    if (!chatId.value) return;
    historyChatList.value = [];
    messageList.value = [];
    page.value = 0;
    loadingStatus.value = false;
    isAnswering.value = false;
    await getChatMessageList();

    scrollToBottom();
  },
  { immediate: true }
);
</script>
<style lang="scss" scoped>
.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;

  padding: 20px 0;
  box-sizing: border-box;
  overflow-y: auto;
}
.identityInformation {
  box-sizing: border-box;
  padding: 0 40px;

  .information {
    display: flex;
    padding: 8px 20px;
    justify-content: space-between;
    align-items: center;
    border: 2px solid #c90000;
    background-color: #fff7f7;
    border-radius: 4px;
    color: #c90000;
    font-weight: 600;
    .identity {
      display: flex;
      font-size: 14px;
    }
  }
  .identity-btn {
    button {
      color: #fff;
      background-color: #c90000;
      cursor: pointer;
      padding: 10px;
      border-radius: 4px;
      font-size: 12px;
    }
  }
}

.chat-main {
  flex: 1;
  background: #f2f2f2;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  overflow: auto;
  padding: 0 40px;

  :deep(.el-textarea__inner) {
    box-shadow: none;
    height: 40px;
    line-height: 40px;
    padding: 0 0 0 17px;
    font-size: 12px;
    color: #232323;
  }
  .chat-content {
    flex: 1;
    overflow: auto;
    scroll-behavior: smooth; //滚动丝滑
    .user-content {
      justify-content: flex-end;
    }
    .content-box {
      display: flex;

      .user-box,
      .system-box {
        display: flex;
        background-color: #fff;
        .chat-head {
          img {
            width: 28px;
            height: 28px;
            margin-right: 11px;
          }
        }
      }
      .user-box {
        align-items: center;
        min-height: 50px;
        width: fit-content;
        padding-left: 20px;
        margin-top: 20px;
        img {
          margin-left: 11px;
        }
      }
      .system-box {
        margin-top: 20px;
        padding: 20px;
      }
    }
  }
  .chat-footer {
    margin-top: 30px;
    position: relative;
    .chat-input {
      background: #fff;

      height: 40px;
      .dialogInput-right {
        height: 40px;
        position: absolute;
        right: 13px;
        bottom: 0;
        display: flex;
        align-items: center;
        .dialog-btn {
          border: none;
          background-color: transparent;
          img {
            width: 14px;
            height: 13px;
          }
        }
      }
    }
  }
}
// markdown样式
.message-markdown {
  :deep(p),
  :deep(h3),
  :deep(ul li),
  :deep(ol li) {
    line-height: 30px;
  }
  :deep(ol),
  :deep(ul) {
    padding-left: 20px;
  }
}
</style>
